package com.hw.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hw.shortlink.project.dao.entity.LinkNetworkStats;
import com.hw.shortlink.project.dto.req.ShortLinkGroupStatsReqDto;
import com.hw.shortlink.project.dto.req.ShortLinkStatsReqDto;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface LinkNetworkStatsMapper extends BaseMapper<LinkNetworkStats> {

    /**
     * 记录短链接访问网络类型数据
     * @param linkNetworkStats
     */
    @Insert("INSERT INTO  tb_link_network_stats(full_short_url,  date, cnt, network, create_time, update_time, del_flag) " +
            "VALUES( #{reqDto.fullShortUrl},  #{reqDto.date}, #{reqDto.cnt}, #{reqDto.network}, " +
            "NOW(), NOW(), 0) " +
            "ON DUPLICATE KEY UPDATE " +
            "cnt = cnt +  #{reqDto.cnt}")
    void shortLinkNetworkStats(@Param("reqDto") LinkNetworkStats linkNetworkStats);

    /**
     * 查询某个短链接访问网络类型
     * @param shortLinkStatsReqDto
     * @return
     */
    @Select("SELECT " +
            "    network, " +
            "    SUM(cnt) AS cnt " +
            "FROM " +
            "    tb_link_network_stats " +
            "WHERE " +
            "    full_short_url = #{reqDto.fullShortUrl} " +
            "    AND date BETWEEN #{reqDto.startDate} and #{reqDto.endDate} " +
            "GROUP BY " +
            "    full_short_url, gid,network")
    List<LinkNetworkStats> listNetworkStatsByShortLink(@Param("reqDto") ShortLinkStatsReqDto shortLinkStatsReqDto);

    //todo fix
    /**
     * 查询某个分组访问网络类型
     * @param shortLinkGroupStatsReqDto
     * @return
     */
    @Select("SELECT " +
            "    network, " +
            "    SUM(cnt) AS cnt " +
            "FROM " +
            "    tb_link_network_stats " +
            "WHERE " +
            "     gid = #{reqDto.gid} " +
            "    AND date BETWEEN #{reqDto.startDate} and #{reqDto.endDate} " +
            "GROUP BY " +
            "    network")
    List<LinkNetworkStats> listNetworkStatsByGroup(@Param("reqDto") ShortLinkGroupStatsReqDto shortLinkGroupStatsReqDto);
}
